import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import { VersioningType } from '@nestjs/common';
// 切换http请求库 fastify， nestjs 默认是 express
// import { FastifyAdapter, NestExpressApplication } from '@nestjs/platform-fastify'; // 需要 npm install fastify @nestjs/platform-fastify

import { NextFunction, Request, Response } from 'express';

import { LoginGuard } from './login.guard'; // 守卫

import { TimeInterceptor } from './time.interceptor';
import * as session from 'express-session';
import { join } from 'path';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    cors: true,
  });
  // const app = await NestFactory.create<NestExpressApplication>(AppModule, new FastifyAdapter()); // 切换至  fastify
  app.useStaticAssets('public', { prefix: '/static' });

  // 设置版本控制
  // header里设置 version: 1
  // app.enableVersioning({
  //   type: VersioningType.HEADER,
  //   header: 'version',
  //   defaultVersion: '1',
  // });

  //  MEDIA_TYPE 是在 accept 的 header 里携带版本号
  // app.enableVersioning({
  //   type: VersioningType.MEDIA_TYPE,
  //   key: 'kk=',
  //   defaultVersion: '1',
  // });

  // URI 放在 url 的后面 http://localhost:3000/v1/users
  // app.enableVersioning({
  //   type: VersioningType.URI,
  // });

  // 自定义版本 http://localhost:3000?hy
  const extractor = (request: Request) => {
    if (request.headers['disable-custom']) {
      return '';
    }
    return request.url.includes('hy') ? '2' : '1';
  };
  app.enableVersioning({
    type: VersioningType.CUSTOM,
    extractor,
  });

  // 设置全局中间件
  // app.use((req: Request, res: Response, next: NextFunction) => {
  //   console.log('请求地址===', req.url);
  //   console.log('中间件开始');
  //   next();
  //   console.log('中间件结束');
  // });

  // 设置全局守卫 方式1
  // app.useGlobalGuards(new LoginGuard());

  // app.useGlobalInterceptors(new TimeInterceptor());

  app.use(
    session({
      secret: 'huangyong',
      cookie: {
        maxAge: 1000 * 60 * 60 * 24 * 7,
      },
    }),
  );

  app.useStaticAssets(join(__dirname, '..', 'public'));
  app.setBaseViewsDir(join(__dirname, '..', 'view'));
  app.setViewEngine('hbs');

  await app.listen(process.env.PORT ?? 3000);

  // setTimeout(() => {
  //   app.close();
  // }, 5000);
}
bootstrap();
